package com.trace.services;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.trace.controller.report.vo.ReportCommentReqVO;
import com.trace.controller.report.vo.ReportContextReqVO;
import com.trace.controller.report.vo.UserReportCommentRespVO;
import com.trace.controller.report.vo.UserReportRespVO;
import com.trace.entity.TReport;
import com.trace.entity.TReportComment;
import com.trace.entity.TReportShareUsers;
import com.trace.entity.TUser;
import com.trace.exception.MessageException;
import com.trace.mapper.TReportCommentMapper;
import com.trace.mapper.TReportMapper;
import com.trace.mapper.TReportShareUsersMapper;
import com.trace.mapper.TUserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServices {
    @Resource
    private TReportMapper tReportMapper;
    @Resource
    private TReportShareUsersMapper shareUsersMapper;
    @Resource
    private TReportCommentMapper reportCommentMapper;
    @Resource
    private TReportShareUsersMapper reportShareUsersMapper;
    @Resource
    private TUserMapper userMapper;

    public Long createReport(ReportContextReqVO reqVO) {
        TReport tReport = new TReport();
        tReport.setReportTime(reqVO.getReportDate());
        tReport.setReportContext(reqVO.getToDayWorkContent());
        tReport.setWorkPlan(reqVO.getTomWorkContent());
        tReport.setAttachmentFileName(reqVO.getAttachmentFileName());
        tReport.setOtherNote(reqVO.getOtherText() != null ? reqVO.getOtherText().getHtml() : null);
        tReport.setCreateDateTime(LocalDateTime.now());
        tReport.setAttachmentPath(reqVO.getAttachmentPath());
        tReport.setReportType(reqVO.getReportType());
        tReport.setUserId(reqVO.getUserId());
        String[] split = reqVO.getShareId().split(",");
        tReportMapper.insert(tReport);
        if (split.length == 0) {
            throw new MessageException("汇报id不能为空!");
        }
        TReportShareUsers shareUsers = new TReportShareUsers();
        for (String shareId : split) {
            shareUsers.setUserId(Long.valueOf(shareId));
            shareUsers.setReportId(tReport.getReportId());
            shareUsersMapper.insert(shareUsers);
        }
        log.info(reqVO.toString());
        return tReport.getReportId();
    }

    public List<UserReportRespVO> getReportByUserId(ReportContextReqVO reqVO) {
        if (reqVO.getUserId() == null ||
                reqVO.getReportType() == null ||
                reqVO.getReceive() == null) {
            throw new MessageException("无效参数!");
        }
        LocalDateTime startOfDay;
        LocalDateTime endOfDay;
        if (StrUtil.isEmpty(reqVO.getReportDate())) {
            LocalDate today = LocalDate.now();
            startOfDay = today.atStartOfDay();
            endOfDay = today.plusWeeks(1).atStartOfDay();
        } else {
            startOfDay = LocalDate.parse(
                    reqVO.getReportDate().split(",")[0],
                    DateTimeFormatter.ISO_DATE
            ).atStartOfDay();
            endOfDay = LocalDate.parse(
                    reqVO.getReportDate().split(",")[1],
                    DateTimeFormatter.ISO_DATE
            ).plusDays(1).atStartOfDay();
        }
        List<UserReportRespVO> respVos;
        if (reqVO.getReceive() == 1) {
            //获取共享表中我的userid的数据
            LambdaQueryWrapper<TReportShareUsers> wrapper1 = new LambdaQueryWrapper<TReportShareUsers>()
                    .eq(TReportShareUsers::getUserId, reqVO.getUserId());
            List<TReportShareUsers> shareUsers = reportShareUsersMapper.selectList(wrapper1);
            List<Long> reportIdList = shareUsers.stream().map(TReportShareUsers::getReportId).distinct().collect(Collectors.toList());
            respVos = tReportMapper.selectReportByRecive(startOfDay, endOfDay, reqVO.getReportType(), reportIdList);
        } else {
            respVos = tReportMapper.selectReportByUserId(startOfDay, endOfDay, reqVO.getReportType(), reqVO.getUserId());
        }

        //这里一次性查询出所有评论太慢了
        for (UserReportRespVO item : respVos) {
            List<TReportShareUsers> shareUsers = reportShareUsersMapper.selectList(new LambdaQueryWrapper<TReportShareUsers>()
                    .eq(TReportShareUsers::getReportId, item.getReportId()));
            List<Long> userIdList = shareUsers.stream().map(TReportShareUsers::getUserId).distinct().collect(Collectors.toList());
            List<TUser> shareUserList = userMapper.selectList(new LambdaQueryWrapper<TUser>().in(TUser::getUserId, userIdList));
            String shareUserName = shareUserList.stream().map(TUser::getUserName).distinct().collect(Collectors.joining(","));
            item.setShareUserName(shareUserName);
            List<UserReportCommentRespVO> comments = reportCommentMapper.selectReportComment(item.getReportId());
            item.setReportComment(comments);
        }

        return respVos;
    }

    /**
     * 创建成功后前端需要重新更新这条报告的评论
     *
     * @param reqVO
     * @return
     */
    public List<UserReportCommentRespVO> createReportComment(ReportCommentReqVO reqVO) {
        TReportComment reportComment = new TReportComment()
                .setReportId(reqVO.getReportId())
                .setUserId(reqVO.getUserId())
                .setContext(reqVO.getCommentContent())
                .setCreateDateTime(LocalDateTime.now());

        int insert = reportCommentMapper.insert(reportComment);
        if (insert == 0) {
            throw new MessageException("保存失败!");
        }
        return reportCommentMapper.selectReportComment(reqVO.getReportId());
    }
}
